package com.hongtech.tiny.modules.app.resolver;

import com.hongtech.tiny.modules.app.annotation.LoginUser;
import com.hongtech.tiny.modules.app.utils.AppJwtUtils;
import com.hongtech.tiny.modules.knowledge.entity.UserEntity;
import com.hongtech.tiny.modules.knowledge.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 */
@Component
public class AppLoginUserResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserService userService;

    @Resource
    private AppJwtUtils appJwtUtils;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserEntity.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        HttpServletRequest req = ((ServletWebRequest) request).getRequest();
        // 获取token
        String token = req.getHeader(appJwtUtils.getAppHeader());
        if (StringUtils.isBlank(token)) {
            token = req.getParameter(appJwtUtils.getAppHeader());
        }
        // 解析token获取当前登录用户
        String mobile = appJwtUtils.getMobileFromToken(token);
        return userService.getUserInfoByMobile(mobile);
    }

}
